<?php
class Dig_Form extends Zend_Form
{
    protected $_instanceId = null;
    public function __construct ($options = array())
    {
        parent::__construct($options);
        // by default set the action to itself and the method to post
        $this->setMethod('post');
        $id = $this->getAttrib('id');
        $this->_instanceId = empty($id) ? 'digitalus_form' : $id;
        // add a hash element
        $this->addElement('hash', $this->_instanceId, array('salt' => 'unique'));
        $requestParams = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        $referrer = $this->addElement('hidden', 'dig_referrer');
        $this->getElement('dig_referrer')->setValue(serialize($requestParams));
        $this->addElement('hidden', 'digitalus_form_instance');
        $this->getElement('digitalus_form_instance')->setValue($this->_instanceId);
    }
    /**
     * this method first determines if the request is a post back
     * if it is it loads the post and validates the form
     * if it is valid then it returns true
     *
     * @return bool
     */
    public function validatePost ()
    {
        $frontController = Zend_Controller_Front::getInstance();
        if ($frontController->getRequest()->isPost() && $_POST['digitalus_form_instance'] == $this->_instanceId) {
            if ($this->isValid($_POST)) {
                return true;
            }
        }
        return false;
    }
    public function getValuesAsModel ($modelClass)
    {
        $modelClass = new $modelClass();
        $modelClass->loadArray($this->getValues());
        return $modelClass;
    }
    public function saveToModel ($modelClass)
    {
        $model = $this->getValuesAsModel($modelClass);
        if ($model instanceof Dig_Model_Abstract) {
            return $model->save();
        }
        return false;
    }
    /**
     * the populate method enables you to populate a form with an instance of Dig_Model
     *
     * @param mixed $data
     */
    public function populate ($data)
    {
        if ($data instanceof Dig_Model_Abstract) {
            $data = $data->toArray();
        }
        parent::populate($data);
    }
    public function getReferrer ()
    {
        $frontController = Zend_Controller_Front::getInstance();
        if ($frontController->getRequest()->isPost()) {
            return unserialize($this->getValue('dig_referrer'));
        }
        return false;
    }
}
?>